package cn.wolfcode.web.interceptor;

import cn.wolfcode.web.annotation.RequiredPermission;
import cn.wolfcode.web.domain.Employee;
import cn.wolfcode.web.service.IPermissionService;
import cn.wolfcode.web.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

public class PermissionInterceptor implements HandlerInterceptor {
    @Autowired
    private HttpSession session;
    @Autowired
    private IPermissionService permissionService;
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
//        方式一:获取session作用域对象的装有账号密码信息的员工对象
//        Employee employee = (Employee) session.getAttribute("employee");
//        方式二:使用抽取的工具类获取session对象,再获取session作用域对象的装有账号密码信息的员工对象
        Employee employee = (Employee)UserContext.getSession().getAttribute(UserContext.EMPLOYEE_IN_SESSION);
        if (employee.getAdmin()) {
            return  true;
        }
//        得到请求的目标方法(当前要执行的控制器类的方法)
        HandlerMethod handlerMethod =(HandlerMethod) handler;
        RequiredPermission annotation = handlerMethod.getMethodAnnotation(RequiredPermission.class);
//       判断请求要访问的处理方法贴的注解是不是空值?空,就就可以访问
        if (annotation==null) {
            return true;
        }
//        如果请求要访问的处理方法贴的注解不是空值,就取出注解的属性表达式字符串
// 跟我们在数据库查询出的这个员工的权限表达式字符串集合比较,如果权限表达式字符串集合包含了.就说明他有这个权限就可以访问.
// 如果没有包含,就没权限跳转到一个提示没有权限的页面给他
        String expression = annotation.expression();
//        annotation.

        List<String> permissions = permissionService.selectByEmpId(employee.getId());
        if (permissions.contains(expression)) {
            return true;
        }
        request.getRequestDispatcher("/WEB-INF/views/common/nopermission.jsp").forward(request,response);
        return false;
    }
}
